package com.jtpay.payresulthelper.util;

import android.content.Context;
import com.jtpay.payresulthelper.BuildConfig;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import static com.jtpay.payresulthelper.util.PayContext.PAYMENT_ALI;
import static com.jtpay.payresulthelper.util.PayContext.PAYMENT_WX;

public class ActivityHelper {

    private static final String aliService = "settings put secure enabled_accessibility_services "
            + BuildConfig.APPLICATION_ID + "/com.jtpay.payresulthelper.service.AliAccessibilityService";
    private static final String wxService = "settings put secure enabled_accessibility_services "
            + BuildConfig.APPLICATION_ID + "/com.jtpay.payresulthelper.service.WeChatAccessibilityService";
    private static final String openService = "settings put secure accessibility_enabled 1";

    private static final String notificationListener = "secure enabled_notification_listeners "
            + BuildConfig.APPLICATION_ID + "/com.jtpay.payresulthelper.service.AliNotificationCollectorService";
    private static final String startNotificationListener = "settings put " + notificationListener;
    private static final String stopNotificationListener = "settings delete secure enabled_notification_listeners";
    /*ali*/

    public static final String ALI_PACKAGE_NAME = "com.eg.android.AlipayGphone";
    private static final String ALI_ACTIVITY_PERSON_CENTER =
            "com.alipay.mobile.security.personcenter.PersonCenterActivity";
    private static final String ALI_ACTIVITY_PROFILE =
            "com.alipay.android.phone.wallet.profileapp.ui.ProfileActivity_";
    public static final String ALI_LAUNCHER_ACTIVITY =
            "com.eg.android.AlipayGphone.AlipayLogin";
    private static final String MSG_BOX_APP_ACTIVITY =
            "com.alipay.android.phone.messageboxapp.ui.MsgboxAppActivity";
    public static final String ALI_BILL_LIST_ACTIVITY_ =
            "com.alipay.mobile.bill.list.ui.BillListActivity_";
    public static final String ALI_BILL_LIST_ACTIVITY =
            "com.alipay.mobile.bill.list.ui.BillListActivity";
    private static final String TRANSFER_HOME_ACTIVITY =
            "com.alipay.mobile.transferapp.ui.TransferHomeActivity_";
    public static final String QR_ACTIVITY_NAME_ =
            "com.alipay.mobile.payee.ui.PayeeQRActivity_";//10.0.20
    public static final String QR_ACTIVITY_NAME =
            "com.alipay.mobile.payee.ui.PayeeQRActivity";//10.1.18
    public static final String QR_SETTING_ACTIVITY_NAME_ =
            "com.alipay.mobile.payee.ui.PayeeQRSetMoneyActivity_";//10.0.20
    public static final String QR_SETTING_ACTIVITY_NAME =
            "com.alipay.mobile.payee.ui.PayeeQRSetMoneyActivity";//10.1.18
    public static final String ALI_USER_LOGIN_ACTIVITY =
            "com.alipay.mobile.security.login.ui.AlipayUserLoginActivity";
    public static final String TRANSFRT_CONFIRM_ACTIVITY =
            "com.alipay.mobile.transferapp.ui.TFToAccountConfirmActivity_";
    public static final String FLY_BIRD_WINDOW_ACTIVITY =
            "com.alipay.android.app.flybird.ui.window.FlyBirdWindowActivity";
    public static final String TRANSFER_SUCCESS =
            "com.alipay.mobile.transferapp.ui.TransferToAccountSuccessActivity_";
    public static final String CHAT_ACTIVITY =
            "com.alipay.mobile.chatapp.ui.PersonalChatMsgActivity_";
    public static final String CHAT_MSG_ACTIVITY =
            "com.alipay.mobile.chatapp.ui.PersonalChatMsgActivity_";
    public static final String ALI_PROGRAM_LAUNCHER_ACTIVITY =
            "com.alipay.mobile.quinox.LauncherActivity";

    /*WeChat*/
    //微信包名
    public static final String WECHAT_PACKAGE_NAME = "com.tencent.mm";
    //微信登录界面
    public static final String WECHAT_LOGIN_PASSWORD_UI_ACTIVITY =
            "com.tencent.mm.ui.account.LoginPasswordUI";
    //微信电话输入界面
    public static final String WECHAT_MOBILE_INPUT_UI_ACTIVITY =
            "com.tencent.mm.ui.account.mobile.MobileInputUI";
    //微信登录界面
    public static final String WECHAT_LOGIN_UI_ACTIVITY = "com.tencent.mm.ui.account.LoginUI";
    //微信主页
    public static final String WECHAT_MAIN_ACTIVITY = "com.tencent.mm.ui.LauncherUI";
    //微信设置二维码备注与金额界面
    public static final String WECHAT_CREATE_CODE_UI =
            "com.tencent.mm.plugin.collect.ui.CollectCreateQRCodeUI";
    public static final String WECHAT_CREATE_CODEUI_DIALOG = "com.tencent.mm.ui.base.i";
    public static final String WECHAT_QRCODE_MODEL = "com.tencent.mm.plugin.collect.b.r";
    public static final String WECHAT_QRCODE_RETURN_MODEL = "com.tencent.mm.ac.k";
    //微信二维码展示界面
    public static final String WECHAT_COLLECT_MAIN_UI =
            "com.tencent.mm.plugin.collect.ui.CollectMainUI";
    public static final String WECHAT_ACTIVITY_PERSON_CENTER =
            "com.tencent.mm.plugin.setting.ui.setting.SettingsPersonalInfoUI";
    public static final String WECHAT_ACTIVITY_PROCEED =
            "com.tencent.mm.plugin.offline.ui.WalletOfflineCoinPurseUI";
    //微信交易记录界面，webview界面
    public static final String WECHAT_ACTIVITY_WEB_VIEW =
            "com.tencent.mm.plugin.webview.ui.tools.WebViewUI";
    //钱包界面
    public static final String WECHAT_ACTIVITY_MALL = "com.tencent.mm.plugin.mall.ui.MallIndexUI";
    public static final String WECHAT_ACTIVITY_MALL_MENU =
            "com.tencent.mm.plugin.mall.ui.MallIndexMenuUI";
    public static final String WECHAT_ACTIVITY_MALL_BALANCE =
            "com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceManagerUI";
    public static final String WECHAT_CLASS_QR_CODE_CLICK_DO_CREATE_METHOD =
            "com.tencent.mm.plugin.collect.b.s";
    private static final String MY_SERVICE =
            "com.jtpay.product.module.accessibilityService.MyAccessibilityService";
    private static final String MY_PACKAGE = BuildConfig.APPLICATION_ID;
    private static final String ALI_PRODUCT_QR_CODE_ACTIVITY =
            "com.jtpay.payresulthelper.ui.activity.MainActivity";

    public static String getTopActivity() {
        String cmd = "dumpsys activity | grep mFocusedActivity";
        //        MainActivity.instance.log("now activity:" + nowactivity);
        return execRootCmd(cmd);
    }

    public static Boolean topActivityEquals(String cName) {
        String cmd = "dumpsys activity | grep mFocusedActivity";
        String nowActivity = execRootCmd(cmd);
//        MainActivity.instance.log("now activity:" + nowActivity);
        return nowActivity.contains(cName);
    }

    public static void openAliService() {
        execRootCmd(aliService);
        execRootCmd(openService);
    }

    public static void openWxService() {
        execRootCmd(wxService);
        execRootCmd(openService);
    }

    public static void openNotificationListener() {
        execRootCmd(startNotificationListener);
    }

    public static void restartNotificationListener() {
        execRootCmd(stopNotificationListener);
        execRootCmd(startNotificationListener);
    }

    public static void stopAliApp() {
        stopApp(ALI_PACKAGE_NAME);
    }

    public static void startAliApp() {
        startActivity(ALI_PACKAGE_NAME, ALI_LAUNCHER_ACTIVITY);
    }

    private static void startActivity(String packageName, String activityName) {
        String cmd = String.format("am start -n %s/%s", packageName,
                activityName);
        execRootCmd(cmd);
    }

    /**
     * Start specifying Activity
     *
     * @param packageName packageName
     */
    private static void stopApp(String packageName) {
        String cmd = String.format("am force-stop %s", packageName);
        execRootCmd(cmd);
    }

    public static void startWeChatActivity(String activityName) {
        startActivity(WECHAT_PACKAGE_NAME, activityName);
    }

    private static void startService(String packageName, String serviceName) {
        String cmd = String.format("am start service -n %s/%s", packageName,
                serviceName);
        execRootCmd(cmd);
    }

    public static void startProgramActivity() {
        startActivity(MY_PACKAGE, ALI_PRODUCT_QR_CODE_ACTIVITY);
    }

    public static void startAlarmActivity() {
        startActivity("com.android.deskclock", "com.android.deskclock.activity.SettingsActivity");
    }

    public static void startQRActivity(Context context) {
        if (PayContext.PAYMENT.equals(PAYMENT_ALI)) {
            new SharedPreferenceUtil().SP_SAVE(context,
                    PayContext.SP_KEY_ALI_PRODUCT_STEP_RESET, "true");
            startActivity(ALI_PACKAGE_NAME, QR_ACTIVITY_NAME);
        } else if (PayContext.PAYMENT.equals(PAYMENT_WX)) {
            startActivity(WECHAT_PACKAGE_NAME, WECHAT_COLLECT_MAIN_UI);
        }
    }

    public static void startBillList() {
        String cmd = String.format("am start -n %s/%s -e category ALL", ALI_PACKAGE_NAME,
                ALI_BILL_LIST_ACTIVITY_);
        execRootCmd(cmd);
    }

    /**
     * auto start screenShot
     */
    public static void screenShot(String path, String name) {
        execRootCmd("screencap -p " + path + "/" + name + "\n");
    }

    /**
     * @param x click coordinate x
     * @param y click coordinate y
     */
    public static void inputClick(int x, int y) {
        execRootCmd(String.format("input tap %s %s", x, y));
    }

    public static void inputClick(String x, String y) {
        execRootCmd(String.format("input tap %s %s \n", x, y));
    }

    public static void inputText(String content) {
        execRootCmd(String.format("input text %s", content));
    }

    //enter  66  , del 67
    public static void inputKeyCode(String keyCode) {
        execRootCmd(String.format("input keyevent %s", keyCode));
    }

    /**
     * Simulated physical sliding
     *
     * @param startX Starting  x coordinate
     * @param startY Starting  y coordinate
     * @param endX   end  x coordinate
     * @param endY   end  x coordinate
     */
    public static void inputSwipe(int startX, int startY, int endX, int endY) {
        String cmd = String.format("input swipe %s %s %s %s", startX,
                startY, endX, endY);
        execRootCmd(cmd);
    }

    public static void startMsgboxAppActivity() {
        startActivity(ALI_PACKAGE_NAME, MSG_BOX_APP_ACTIVITY);
    }

    public static void startTransferActivity() {
        startActivity(ALI_PACKAGE_NAME, TRANSFER_HOME_ACTIVITY);
    }

    public static void startPersonCenterActivity() {
        startActivity(ALI_PACKAGE_NAME, ALI_ACTIVITY_PERSON_CENTER);
    }

    public static void startAliProgram() {
        startActivity(ALI_PACKAGE_NAME, ALI_LAUNCHER_ACTIVITY);
    }

    public static void startProfileActivity() {
        startActivity(ALI_PACKAGE_NAME, ALI_ACTIVITY_PROFILE);
    }

    public static void startMyService() {
        startService(MY_PACKAGE, MY_SERVICE);
    }

    public static void startWXPersonCenterActivity() {
        startActivity(WECHAT_PACKAGE_NAME, WECHAT_ACTIVITY_PERSON_CENTER);
    }

    private static String execRootCmd(String cmd) {
        String result = "";
        DataOutputStream dos = null;
        DataInputStream dis = null;
        Process p = null;
        try {
            p = Runtime.getRuntime().exec("su");// 经过Root处理的android系统即有su命令
            dos = new DataOutputStream(p.getOutputStream());
            dis = new DataInputStream(p.getInputStream());

            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            String line;
            while ((line = dis.readLine()) != null) {
                result += line;
            }
            p.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionUtil.getInstance().saveExceptionFile(
                    "ActivityHelper execRootCmd Exception = "
                            + e.getMessage());
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    ExceptionUtil.getInstance().saveExceptionFile(
                            "ActivityHelper execRootCmd " +
                                    "IOException = " + e.getMessage());
                }
            }
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    ExceptionUtil.getInstance().saveExceptionFile(
                            "ActivityHelper execRootCmd " +
                                    "IOException = " + e.getMessage());
                }
            }
            if (p != null) {
                p.destroy();
            }
        }
        return result;
    }
}
